// 浏览器环境检测
export const isBrowser = typeof window !== "undefined";

// 获取用户代理信息（缓存结果，避免重复计算）
export const getUA = () => {
  if (!isBrowser) return "";
  return window.navigator.userAgent.toLowerCase();
};

// 检测是否为移动设备
export const isMobileDevice = () => {
  if (!isBrowser) return false;
  const ua = getUA();
  const platform = window.navigator.platform.toLowerCase();
  const mobileKeywords = [
    "android",
    "iphone",
    "ipad",
    "ipod",
    "blackberry",
    "windows phone",
    "iemobile",
    "opera mini",
    "mobile",
  ];
  return mobileKeywords.some((keyword) => ua.includes(keyword) || platform.includes(keyword));
};

// 检测是否为 iOS 设备
export const isIOS = () => {
  if (!isBrowser) return false;
  const ua = getUA();
  return /iphone|ipad|ipod|ios/.test(ua);
};

// 检测是否为 Android 设备
export const isAndroid = () => {
  if (!isBrowser) return false;
  const ua = getUA();
  return /android/.test(ua);
};

// 检测是否为微信环境
export const isWeChat = () => {
  if (!isBrowser) return false;
  const ua = getUA();
  return /micromessenger/.test(ua);
};

// 检测是否为企业微信
export const isWeChatWork = () => {
  if (!isBrowser) return false;
  const ua = getUA();
  return isWeChat() && /wxwork/.test(ua);
};

// 节流函数（优化版）
export const throttle = (func, delay) => {
  let lastCall = 0;
  return function (...args) {
    const now = Date.now();
    if (now - lastCall >= delay) {
      func.apply(this, args);
      lastCall = now;
    }
  };
};

// 清除所有定时器（优化版）
export const clearAllTimers = () => {
  if (!isBrowser) return;
  let maxId = setTimeout(() => {}, 0);
  for (let i = 1; i <= maxId; i++) {
    clearTimeout(i);
    clearInterval(i);
  }
};


// if (isMobileDevice()) {
//   console.log("当前是移动设备");
// } else {
//   console.log("当前是电脑设备");
// }

// if (isIOS()) {
//   console.log("当前是 iOS 设备");
// }

// if (isWeChat()) {
//   console.log("当前在微信环境中");
// }